package cn.lzm.proxy;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.lizemin.entity.RpcRequest;
import cn.lizemin.entity.RpcResponse;
import cn.lizemin.entity.User;
import cn.lizemin.service.UserApi;
import cn.lzm.serializer.JDKSerializer;
import cn.lzm.serializer.Serializer;

/**
 * @author lzm
 * @Date 2024/7/20
 * @description 这里的第一版先使用静态代理来实现接口调用
 */
public class UserServiceProxy implements UserApi {

    @Override
    public User getUserById(Integer id) {
        RpcRequest req = new RpcRequest();
        req.setServiceName(UserApi.class.getName());
        req.setMethodName("getUserById");
        req.setArgs(new Object[]{id});
        req.setArgTypes(new Class[]{Integer.class});

        Serializer serializer = new JDKSerializer();
        byte[] reqData = serializer.serialize(req);
        try (HttpResponse resp = HttpRequest.post("http://localhost:8402")
                .body(reqData)
                .execute()) {
            byte[] result = resp.bodyBytes();
            RpcResponse response = serializer.deserialize(result, RpcResponse.class);
            Object responseData = response.getData();
            return (User) responseData;
        } catch (Exception ex) {
            System.out.println(ExceptionUtil.getThrowableList(ex));
        }
        return null;
    }


}
